package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.PageResult;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.common.UserHolder;
import com.itheima.ydd.entity.*;
import com.itheima.ydd.service.*;
import com.sun.xml.internal.bind.v2.runtime.unmarshaller.TagName;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.ResultSet;
import java.util.List;
import java.util.function.LongFunction;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/ydd_tag")
public class TagController {

    @Autowired
    private TagService tagService;

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private RoleMenuService roleMenuService;

    @Autowired
    private MenuService menuService;
    /**
     * 分页查询
     * @param tagname
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/list")
    public ResultData list(String tagname,Long page,Long limit){
        log.info(page.toString());
        log.info(limit.toString());
        //分页构造器
        Page tagPage = new Page(page,limit);
        //条件构造器
        LambdaQueryWrapper<Tag> queryWrapper = new LambdaQueryWrapper<>();
        //判断条件是否为空
        queryWrapper.like( !(tagname==null),Tag::getTagname,tagname);


//        if (!("".equals(tagname))){
//            queryWrapper.eq(Tag::getTagname,tagname);
//        }
        tagService.page(tagPage,queryWrapper);
        return ResultData.ok("", PageResult.init(tagPage.getTotal(),page,limit,tagPage.getRecords()));
    }

    /**
     * 添加标签
     * @param tag
     * @return
     */
//    @PostMapping("/add")
//    public ResultData add(@RequestBody Tag tag){
//        log.info("添加：{}",tag);
//        tagService.save(tag);
//        return ResultData.ok("",tag);
//    }

    //新增
    @PostMapping("add")
    public ResultData add(@RequestBody Tag tag) {
        log.info("新增启动");
        //权限管理
        LambdaQueryWrapper<Role> qlw = new LambdaQueryWrapper<>();
        //获取用户登陆的id  转化为string类型  --前端页码传来的值带有【】 ""  所以要去除点
        String userId = UserHolder.getUserId();
        User user1 = userService.getById(userId);
        //分割
        String strip = StringUtils.strip(user1.getRole_id(), "[]");
        String[] split = strip.split(",");
        for (int i = 0; i < split.length; i++) {
            //代替    --去除
            split[i] = StringUtils.replace(split[i], "\"", "");
        }
        qlw.in(Role::getId, split);
        List<Role> list = roleService.list(qlw);
        List<String> collect = list.stream().map((item) -> {
            return item.getId();
        }).collect(Collectors.toList());
        LambdaQueryWrapper<RoleMenu> qlw2 = new LambdaQueryWrapper<>();
        qlw2.in(RoleMenu::getRoleId, collect);
        List<RoleMenu> list1 = roleMenuService.list(qlw2);
        for (RoleMenu roleMenu : list1) {
            String menuId = roleMenu.getMenuId();
            Menu menu = menuService.getById(menuId);
            //一级权限
            if ("内容管理".equals(menu.getTitle())) {
                LambdaQueryWrapper<Menu> qlw3 = new LambdaQueryWrapper<>();
                qlw3.eq(Menu::getPid, menuId);
                List<Menu> list2 = menuService.list(qlw3);
                //二级缓存
                for (Menu menu1 : list2) {
                    if ("标签管理".equals(menu1.getTitle())){
                        LambdaQueryWrapper<Menu> qwl4= new LambdaQueryWrapper<>();
                        qwl4.eq(Menu::getPid,menu1.getId());
                        List<Menu> list3=menuService.list(qwl4);
                        for (Menu menu2 : list3) {
                            //三级缓存
                            if ("增加".equals(menu2.getTitle())){
                                tagService.save(tag);
                                return ResultData.ok("新增成功", tag);
                            }
                        }
                    }
                }
            }
        }

        return ResultData.error("权限不足不能添加");
    }

    /**
     * 回显数据
     * @param id
     * @return
     */
    @GetMapping("/rowInfo")
    public ResultData echo(Long id){
        log.info("根据id：{}回显数据",id);
        Tag tag = tagService.getById(id);
        return ResultData.ok("",tag);
    }

    /**
     * 修改数据
     * @param tag
     * @return
     */
//    @PostMapping("/update")
//    public ResultData update(@RequestBody Tag tag){
//        log.info("修改数据：{}",tag);
//        tagService.updateById(tag);
//        return ResultData.ok("修改成功","");
//    }
    @PostMapping("update")
    public ResultData update(@RequestBody Tag tag) {
        log.info("修改启动"); //权限管理
        LambdaQueryWrapper<Role> qlw = new LambdaQueryWrapper<>();
        //获取用户登陆的id  转化为string类型  --前端页码传来的值带有【】 ""  所以要去除点
        String userId = UserHolder.getUserId();
        User user1 = userService.getById(userId);
        //分割
        String strip = StringUtils.strip(user1.getRole_id(), "[]");
        String[] split = strip.split(",");
        for (int i = 0; i < split.length; i++) {
            //代替    --去除
            split[i] = StringUtils.replace(split[i], "\"", "");
        }
        qlw.in(Role::getId, split);
        List<Role> list = roleService.list(qlw);
        List<String> collect = list.stream().map((item) -> {
            return item.getId();
        }).collect(Collectors.toList());
        LambdaQueryWrapper<RoleMenu> qlw2 = new LambdaQueryWrapper<>();
        qlw2.in(RoleMenu::getRoleId, collect);
        List<RoleMenu> list1 = roleMenuService.list(qlw2);
        for (RoleMenu roleMenu : list1) {
            String menuId = roleMenu.getMenuId();
            Menu menu = menuService.getById(menuId);
            //一级权限
            if ("内容管理".equals(menu.getTitle())) {
                LambdaQueryWrapper<Menu> qlw3 = new LambdaQueryWrapper<>();
                qlw3.eq(Menu::getPid, menuId);
                List<Menu> list2 = menuService.list(qlw3);
                //二级缓存
                for (Menu menu1 : list2) {
                    if ("标签管理".equals(menu1.getTitle())){
                        LambdaQueryWrapper<Menu> qwl4= new LambdaQueryWrapper<>();
                        qwl4.eq(Menu::getPid,menu1.getId());
                        List<Menu> list3=menuService.list(qwl4);
                        for (Menu menu2 : list3) {
                            //三级缓存
                            if ("更新".equals(menu2.getTitle())){
                                tagService.updateById(tag);
                                return ResultData.ok("修改成功", tag);
                            }
                        }
                    }
                }
            }
        }

        return ResultData.error("权限不足不能修改");

    }

    /**
     * 根据id删除数据
     * @param id
     * @return
     */
//    @GetMapping("/del")
//    public ResultData delete(Long id){
//        log.info("根据id：{}删除数据",id);
//        tagService.removeById(id);
//        return ResultData.ok("删除成功","");
//
//    }
    @GetMapping("del")
    public ResultData del(Integer id) {
        log.info("删除启动");
        Tag tag = tagService.getById(id);
        if ("1".equals(tag.getDefaultData())) {
            return ResultData.error("默认数据无法删除");
        }
        //权限管理
        LambdaQueryWrapper<Role> qlw = new LambdaQueryWrapper<>();
        //获取用户登陆的id  转化为string类型  --前端页码传来的值带有【】 ""  所以要去除点
        String userId = UserHolder.getUserId();
        User user1 = userService.getById(userId);
        //分割
        String strip = StringUtils.strip(user1.getRole_id(), "[]");
        String[] split = strip.split(",");
        for (int i = 0; i < split.length; i++) {
            //代替    --去除
            split[i] = StringUtils.replace(split[i], "\"", "");
        }
        qlw.in(Role::getId, split);
        List<Role> list = roleService.list(qlw);
        List<String> collect = list.stream().map((item) -> {
            return item.getId();
        }).collect(Collectors.toList());
        LambdaQueryWrapper<RoleMenu> qlw2 = new LambdaQueryWrapper<>();
        qlw2.in(RoleMenu::getRoleId, collect);
        List<RoleMenu> list1 = roleMenuService.list(qlw2);
        for (RoleMenu roleMenu : list1) {
            String menuId = roleMenu.getMenuId();
            Menu menu = menuService.getById(menuId);
            //一级权限
            if ("内容管理".equals(menu.getTitle())) {
                LambdaQueryWrapper<Menu> qlw3 = new LambdaQueryWrapper<>();
                qlw3.eq(Menu::getPid, menuId);
                List<Menu> list2 = menuService.list(qlw3);
                //二级缓存
                for (Menu menu1 : list2) {
                    if ("标签管理".equals(menu1.getTitle())){
                        LambdaQueryWrapper<Menu> qwl4= new LambdaQueryWrapper<>();
                        qwl4.eq(Menu::getPid,menu1.getId());
                        List<Menu> list3=menuService.list(qwl4);
                        for (Menu menu2 : list3) {
                            //三级缓存
                            if ("删除".equals(menu2.getTitle())){
                                tagService.removeById(id);
                                return ResultData.ok("删除成功", "");
                            }
                        }
                    }
                }
            }
        }

        return ResultData.error("权限不足不给删除");
    }
    /**
     *  all 方法
     * @return
     */
    @GetMapping("/all")
    public ResultData all(){
        List<Tag> list = tagService.list();
        return ResultData.ok("",list);
    }

}
